package cn.codeforfun.base;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * @author wangbin
 */
public class BaseService<E extends BaseEntity, R extends BaseRepository<E>> {
    protected R repository;

    public BaseService(R repository) {
        this.repository = repository;
    }

    public Page<E> listPage(Pageable pageable) {
        return repository.findAllByDeletedFalse(pageable);
    }

    public E getById(@PathVariable String id) {
        return repository.findFirstByIdAndDeletedFalse(id).orElse(null);
    }

    public void save(@RequestBody E e) {
        repository.save(e);
    }

    public void deleteById(@PathVariable String id) {
        E e = repository.findById(id).orElseThrow(NullPointerException::new);
        e.setDeleted(true);
        repository.save(e);
    }
}
